import Axios from 'axios'

const user = {
    state: {
        user: null,
    },
    getters: {
        user: state => state.user,
    },
    mutations: {
        SET_USER(state, data) {
            state.user = data
        },
    },
    actions: {
        user_login({ commit }, data) {
            return new Promise((resolve, reject) => {
                Axios
                    .post('/user/login', data)
                    .then(res => {
                        localStorage.setItem("higame-token", res.token)
                        commit('SET_USER', res.data)
                        setTimeout(() => {
                            userCheck(commit)
                        }, loopTime);

                        resolve(res)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },

        user_register({ commit }, data) {
            return new Promise((resolve, reject) => {
                Axios
                    .post('/user/register', data)
                    .then(res => {
                        resolve(res)
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },

        user_logout({ commit }) {
            commit('SET_USER', null)
            localStorage.removeItem("higame-token")
            clearInterval(checkInterval)
            checkInterval = null
        },

        user_check({ commit }) {
            userCheck(commit)
        }
    }
}
let checkInterval = null;
let loopTime = 1000 * 60 * 15;
function userCheck(func) {
    return new Promise((resolve, reject) => {
        Axios
            .post('/user/check', {})
            .then(res => {
                func('SET_USER', res.data)
                localStorage.setItem("higame-token", res.token)
                if (checkInterval == null) {
                    checkInterval = setInterval(() => {
                        userCheck(func)
                    }, loopTime);
                }

                resolve(res)
            })
            .catch(error => {
                func('SET_USER', null)
                reject(error)
            })
    })
}
export default user